﻿package com.hodgedev.net.drupal 
{
	import flash.errors.IllegalOperationError;
	import flash.events.EventDispatcher;
	import flash.net.NetConnection;
	import flash.net.ObjectEncoding;
	/**
	 * Handles connection to Drupal AMFPHP module.
	 * Utilizes System class to establish the
	 * connection.  Holds references to the Session
	 * ID and NetConnection object for use by other
	 * classes, such as Node, View, Comments.
	 * @author Brian Hodge (brian@hodgedev.com)
	 */
	public class Services extends EventDispatcher
	{
		private static var _instance:Services;
		private var _gateway:String;
		private var _nc:NetConnection;
		private var _system:System;
		private var _sessid:String;
		private var _connected:Boolean;
		
		public static function getInstance(pGateway:String = null):Services
		{
			if (!Services._instance) Services._instance = new Services(new PrivateClass());
			return _instance;
		}
		public function Services(pPrivateClass:PrivateClass):void
		{
			if (!pPrivateClass) throw new IllegalOperationError("Cannot instantiate Services Singleton class;  Use the static getInstance() method");
			
			_nc = new NetConnection();
			_nc.objectEncoding = ObjectEncoding.AMF3;
			_system = new System();
		}
		private function _onSystemConnected(e:SystemEvent):void
		{
			_system.removeEventListener(SystemEvent.CONNECTED, _onSystemConnected);
			_sessid = e.sessid;
			_connected = true;
			trace("Connected: " + _connected);
			dispatchEvent(new ServicesEvent(ServicesEvent.SYSTEM_CONNECTED));
		}
		public function connect(pGateway:String = null):void
		{
			trace("Attempting to connect");
			if (pGateway) _gateway = pGateway;
			if (_gateway == null) throw(new Error("Services gateway must not be null"));
			_system.addEventListener(SystemEvent.CONNECTED, _onSystemConnected);
			_system.connect(_nc, pGateway);
		}
		public function close():void
		{
			_connected = false;
			_system.close();
			trace("Connection Closed");
		}
		public function get gateway():String
		{
			return _gateway;
		}
		public function set gateway(pGateway:String):void
		{
			_gateway = pGateway;
		}
		public function get netConnection():NetConnection
		{
			return _nc;
		}
		public function get sessid():String
		{
			return _sessid;
		}
		public function get connected():Boolean
		{
			return _connected;
		}
	}
}
internal class PrivateClass
{
	function PrivateClass():void
	{
		//
	}
}